//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by 郭平 on 15/10/8.
//  Copyright © 2015年 郭平. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController, UIWebViewDelegate {

    var webView : UIWebView {
        get {
            return view as! UIWebView
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        let rightBar = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Done, target: self, action: "defaultAccount")
        
        navigationItem.rightBarButtonItem = rightBar
        
        loadOAuthPage()
        
    }

    // 自动填充
    func defaultAccount() {
        let script = "document.getElementById('userId').value='';document.getElementById('passwd').value='"
        self.webView.stringByEvaluatingJavaScriptFromString(script)

    }
    // 关闭页面
    @IBAction func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    // 显示页面
    private func loadOAuthPage(){
    
        webView.loadRequest(NSURLRequest(URL: NetworkTools.shatedToos.OAuthURL()))
        
    }
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let requestURL = request.URL!.absoluteString
        
        if requestURL.hasPrefix("https://api.weibo.com/") {
        
            return true
        }
        
        // 过滤掉没用的url请求
        if !requestURL.hasPrefix(NetworkTools.shatedToos.WB_redirect_uri){
        
            return false
        }
        
        if let query = request.URL?.query {
            
            let codeStr = "code="
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            print("--",code)
           loadAccessToken(code)
        }
        return false
    }
    
    // 请求用户token
    private func loadAccessToken(code: String) {
    
        NetworkTools.shatedToos.loadAccessToken(code) { (dict, error) -> () in
            
            if error != nil {
                
                SVProgressHUD.showInfoWithStatus("网络连接失败")
                return
            }
            
            // 获取数据成功
            
            let account = UserAccount(dict: dict!)
            account.loadUserInfo({ (error) -> () in
                if error != nil {
                    SVProgressHUD.showWithStatus("网络连接失败!!")
                    return
                }
    
                let window = UIApplication.sharedApplication().delegate?.window!
                window?.rootViewController = WelcomeViewController()
            })
        }
    }
    
    //MARK: webViewDelegate
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    override func viewDidDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        let jsstring = "document.title"
        let webTitle = webView.stringByEvaluatingJavaScriptFromString(jsstring)
       title = webTitle
        SVProgressHUD.dismiss()
    }
    

}
